package it.secse.idmadaption.plugin;

import it.secse.idmadaption.engine.IDMAdapter;
import it.secse.idmadaption.parser.ConfigParser;
import it.secse.idmadaption.plugin.util.CredentialData;
import it.secse.idmadaption.plugin.util.DelegationFrameworkWrapper;
import it.secse.idmadaption.plugin.util.DelegationFrameworkWrapperIF;

import java.io.FileNotFoundException;
import java.util.Calendar;
import java.util.TimeZone;

import javax.xml.crypto.dsig.XMLObject;
import javax.xml.stream.XMLStreamException;

import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.impl.builder.StAXOMBuilder;
import org.apache.axiom.om.impl.llom.util.AXIOMUtil;
import org.apache.axiom.soap.impl.dom.SOAPEnvelopeImpl;
import org.apache.axis2.MyClient.MyServiceClient;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.context.ConfigurationContextFactory;
import org.apache.neethi.Policy;
import org.apache.neethi.PolicyEngine;
import org.apache.rampart.RampartMessageData;
import org.apache.xmlbeans.XmlObject;
import org.tempuri.CredentialProviderServiceStub.GetSecurityTokenForDelegateeResponse;

public class WSSUSRTokenPlugin extends AbstractPlugin {
	
	boolean isDelegated = false;

	
	public Object manage(String operationName, String realEndPoint,
			Object clientRequest, String delegator, String callback) {
		
		
		try {
			
			System.out.println("INSTANTIATED!!!!");
			CredentialData data = CredentialData.getInstance();
			String username = IDMAdapter.getParser().getDocument().getElementsByTagName("Username").item(0).getFirstChild().getNodeValue();			
			data.setUsername(username);
			String password = IDMAdapter.getParser().getDocument().getElementsByTagName("Password").item(0).getFirstChild().getNodeValue();
			data.setPassword(password);
			String role = IDMAdapter.getParser().getDocument().getElementsByTagName("Role").item(0).getFirstChild().getTextContent();
						
			DelegationFrameworkWrapper wrapper = new DelegationFrameworkWrapper();
			GetSecurityTokenForDelegateeResponse delegationResponse = wrapper.delegate(role, username, delegator, callback);
			
//			if (delegationResponse.getGetSecurityTokenForDelegateeResult().getUsernameToken().getUsername().equals(username)) {
//				
//				
//			}
			
			
			
				//CONTESTO:
				// siamo AXIS2 abbiamo una WS-SecurityPolicy quindi usiamo RAMPART
			
			
			// dove andare a prendere le .mar (moduli) librerie di Rampart e Addressing
			ConfigurationContext ctx = ConfigurationContextFactory.createConfigurationContextFromFileSystem("files\\google\\build\\client_repository", null);
        
        
			//Istruzioni rampart
			MyServiceClient client = new MyServiceClient(ctx, null);
			
        Options options = new Options();
        String namespace = IDMAdapter.getParser().getDocument().getElementsByTagName("TargetNamespace").item(0).getFirstChild().getNodeValue();
        System.out.println(namespace);
        options.setAction(namespace + ":" + operationName);
        options.setTo(new EndpointReference(realEndPoint));
        options.setProperty(RampartMessageData.KEY_RAMPART_POLICY, ConfigParser.loadPolicy(operationName));
        client.setOptions(options);
        
        client.engageModule("addressing");
        client.engageModule("rampart");	
//      OMElement response = client.sendReceive(getPayload("Hello world"));
        
        //Chiamo il servizio concreto
		XmlObject xmlRequest = (XmlObject) clientRequest;
		OMElement soapElement = AXIOMUtil.stringToOM(xmlRequest.xmlText());
		//preparation don, now call
		System.out.println("Calling service at " + Calendar.getInstance().getTime().toString());
		System.out.println(soapElement);
		Object response = client.sendReceive(soapElement);
	
		OMElement castedResp = (OMElement) response; 
		XmlObject newResp = XmlObject.Factory.parse(castedResp.getXMLStreamReader());

	

    //    OMElement response = client.sendReceive(clientRequest);
		System.out.println(options.getAction());
		System.out.println(newResp.toString());
        System.out.println("FINISH_OK");
        return newResp;
		
		} catch (java.lang.Exception e) {
			e.printStackTrace();
		}
		
		
		System.out.println("FINISH_KO");
		return null;
	}
	
	    
//	    private static OMElement getRequest () {
//			try {
//                
//				CheckScheduleDocument request = CheckScheduleDocument.Factory.newInstance();
//				CheckScheduleDocument.CheckSchedule  param = CheckScheduleDocument.CheckSchedule.Factory.newInstance();
//				param.setStrMailbox("gianluca.ripa@gmail.com");
//
//				// SISTEMARE ORE +2
//				Calendar arg0 = Calendar.getInstance();	
//				arg0.add(Calendar.HOUR_OF_DAY, 2);
//				TimeZone zone = arg0.getTimeZone();
//				param.setStart(arg0);
//				System.out.println(arg0.getTimeZone().toString());
//				Calendar arg1 = Calendar.getInstance();
//				arg1.add(Calendar.HOUR_OF_DAY, 4);
//				param.setEnd(arg1);			
//				System.out.println(arg1.getTime().toLocaleString());
//				request.setCheckSchedule(param);
//				
//				XmlObject xmlRequest = (XmlObject) request;
//				OMElement soapElement;
//				soapElement = AXIOMUtil.stringToOM(xmlRequest.xmlText());
//				return(soapElement);
//			
//			} catch (XMLStreamException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}
//			return null;
//
//	    }
	 

}
